package com.siki.api.controller;

import com.siki.api.pojo.Dept;
import com.siki.api.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/dept")
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "getDept/{id}")
    public Dept getDept(@RequestBody @Validated @PathVariable("id") Long id) {
        return deptService.queryDept(id);
    }

    @RequestMapping(value = "getAll")
    public List<Dept> getDept(){
        return deptService.queryAllDept();
    }

    @RequestMapping(value = "addDept")
    public boolean addDept(@RequestBody Dept dept){
        return deptService.addDept(dept);
    }

    @RequestMapping(value = "getDiscovery")
    public Object getDiscovery(){
        List<String> services = discoveryClient.getServices();
        services.stream().forEach(
                s -> {
                    System.out.println(s);
                }
        );

        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        instances.stream().forEach(serviceInstance -> {
            System.out.println(
                    serviceInstance.getHost()+"\t"+
                            serviceInstance.getInstanceId()+"\t"+
                            serviceInstance.getServiceId()+"\t"+
                            serviceInstance.getUri()+"\t"+
                            serviceInstance.getPort()
            );
        });
        return this.discoveryClient;
    }
}
